package com.gz.mylife.app;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.adapter.ShoppingCartAdapter;
import com.gz.mylife.adapter.ShoppingCartAdapter.UpdataUI;
import com.gz.mylife.util.ToastUtils;
import com.gz.mylife.widget.LoadingCover;
import com.gz.mylife.widget.OfflineDialog;
import com.gz.mylife.widget.LoadingCover.OnLoadingCoverRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zl.smartmall.library.IShoppingCart;
import com.zl.smartmall.library.listener.DeleteGoodsListener;
import com.zl.smartmall.library.listener.ShoppingCartListener;
import com.zl.smartmall.library.po.ShoppingCartInfo;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.Tools;

public class FragmentShoppingCart extends Fragment implements OnClickListener,OnLoadingCoverRefreshListener,OnRefreshListener<ListView> {

	private static final String TAG = FragmentShoppingCart.class.getSimpleName();

	private Context mContext;

	private View mConvertView;
	private PullToRefreshListView mListView;
	private ImageView mIvAllSelected;
	private TextView mTvAllSelected;
	private TextView mProductTotal;
	private TextView mProductPriceTotal;
	private TextView mProductPriceTotalTitle1;
	private TextView mProductPriceTotalTitle2;
	private RelativeLayout  mBtnOrder;
	private LoadingCover mLoadingCover;
	private Dialog mLoadingData;
	private RelativeLayout mFootview;
	private OfflineDialog mOfflineDialog;

	private List<ShoppingCartInfo> mDataList;
	private ShoppingCartAdapter mAdatper;
	private MyShoppingCartListener mShoppingListener;
	private DeleteGoodsListener mDeleteGoodsListener;
	private ShoppingCartListener mShoppingCartListener;
	private MyUpdataUI mUpdataUI;
	private boolean mIsAllseleted;
	private int mProductTotalNum = 0;
	private double mProductPriceTotalNum = 0;
	
	private ImageView ivEdit;
	private TextView tvEdit;
	private boolean isEditable = false;
	private String mDeleteStr;
	private RefreshReceiver mRefreshReceiver;
	
	private int immediateShopId = -1;
	private int immediateProductId = -1;
	private boolean immediate = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		CrashHandler.d(TAG, TAG + " onCreate");
		mRefreshReceiver = new RefreshReceiver();
		IntentFilter intentFilter = new IntentFilter(Define.ACTION_REFRESH_SHOPPING_CART);
		getActivity().registerReceiver(mRefreshReceiver, intentFilter);
		
	}
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		CrashHandler.d(TAG, TAG + " onCreateView");
		if (mConvertView == null) {
			CrashHandler.d(TAG, "convertView is null, init the whole elements");
			mConvertView = inflater.inflate(R.layout.fragment_shopping_cart,
					container, false);
			init(inflater);
		}
//		 ((BaseActionBarActivity) getActivity()).mActionBar.setTitle("营养专栏");
		setHasOptionsMenu(true);
		
		mDataList = new ArrayList<ShoppingCartInfo>();
		mUpdataUI = new MyUpdataUI(this);
		mAdatper = new ShoppingCartAdapter(getActivity(), mDataList, mUpdataUI);
		mListView.setAdapter(mAdatper);
		mShoppingListener = new MyShoppingCartListener(this);
		loadData();
		return mConvertView;
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//		inflater.inflate(R.menu.shopping_cart, menu);
//		MenuItem mItemEdit2 = menu.findItem(R.id.action_edit2);
//		View mItemEdit2View = MenuItemCompat.getActionView(mItemEdit2);
//		ivEdit = (ImageView) mItemEdit2View.findViewById(R.id.iv_edit);
//		tvEdit = (TextView) mItemEdit2View.findViewById(R.id.tv_edit);
//		ivEdit.setVisibility(View.GONE);
//		mItemEdit2View.setOnTouchListener(new OnTouchListener() {
//			
//			@Override
//			public boolean onTouch(View v, MotionEvent event) {
//				switch (event.getAction()) {
//				case MotionEvent.ACTION_DOWN:
//					v.setBackgroundResource(R.drawable.bg_actionbar_menu_pressed);
//					break;
//				case MotionEvent.ACTION_CANCEL:
//				case MotionEvent.ACTION_UP:
//					v.setBackgroundResource(R.color.transparent);
//					break;
//				}
//				return false;
//			}
//		});
//		if(isEditable){
//			tvEdit.setText("完成");
//		}else{
//			tvEdit.setText("修改");
//		}
//		mItemEdit2View.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				if(isEditable){
//					JSONArray orderArray = new JSONArray();
//					for(int i = 0;i < mDataList.size();i++){
//						ShoppingCartInfo info = mDataList.get(i);
//						JSONObject order = new JSONObject();
//						try {
//							order.put("act_id", info.getActId());
//							order.put("shop_id", info.getShopId());
//							order.put("product_id", info.getProductId());
//							order.put("num", info.getAddNum());
//						} catch (JSONException e) {
//							e.printStackTrace();
//						}
//						if(info.getAddNum() != 0){
//							orderArray.put(order);
//						}
//					}
//					if(orderArray.length()>0){
//							mLoadingData.show();
//							mDeleteStr = Tools.Base64Encode(orderArray.toString());//Base64.encodeToString(orderArray.toString().getBytes(), Base64.DEFAULT);
//							IShoppingCart.getInstance().upDataGoods(mDeleteStr, mShoppingListener);
//					}else{
//						tvEdit.setText("修改");
//						isEditable = false;
//						mProductPriceTotalTitle1.setVisibility(View.VISIBLE);
//						mProductPriceTotalTitle2.setVisibility(View.VISIBLE);
//						mProductPriceTotal.setVisibility(View.VISIBLE);
//						mIvAllSelected.setVisibility(View.VISIBLE);
//						mTvAllSelected.setVisibility(View.VISIBLE);
//						if(isEditable){
//							mBtnOrder.setText("删除");
//						}else{
//							mBtnOrder.setText("结账");
//						}
//						mAdatper.setEditable(isEditable);
//						mAdatper.notifyDataSetChanged();
//					}
//				}else{
//					tvEdit.setText("完成");
//					isEditable = true;
//					mProductPriceTotalTitle1.setVisibility(View.GONE);
//					mProductPriceTotalTitle2.setVisibility(View.GONE);
//					mProductPriceTotal.setVisibility(View.GONE);
//					mIvAllSelected.setVisibility(View.GONE);
//					mTvAllSelected.setVisibility(View.GONE);
//					if(isEditable){
//						mBtnOrder.setText("删除");
//					}else{
//						mBtnOrder.setText("结账");
//					}
//					mAdatper.setEditable(isEditable);
//					mAdatper.notifyDataSetChanged();
//				}
//			}
//		});
//		
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public void onDetach() {
		// TODO Auto-generated method stub
		super.onDetach();
		// try {
		// Field childFragmentManager =
		// Fragment.class.getDeclaredField("mChildFragmentManager");
		// childFragmentManager.setAccessible(true);
		// childFragmentManager.set(this, null);
		// } catch (NoSuchFieldException e) {
		// throw new RuntimeException(e);
		// } catch (IllegalAccessException e) {
		// throw new RuntimeException(e);
		// }
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		CrashHandler.d(TAG, TAG + " onDestroy");
		mShoppingListener.release();
		mUpdataUI.release();
		getActivity().unregisterReceiver(mRefreshReceiver);
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		CrashHandler.d(TAG, TAG + " onDestroyView");
		((ViewGroup) mConvertView.getParent()).removeView(mConvertView);
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		CrashHandler.d(TAG, TAG + " onPause");
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		CrashHandler.d(TAG, TAG + " onResume");
		// mGridAdapter.notifyDataSetChanged();
	}

	public void checkNoData() {
		if(mDataList.size() == 0){
			if(mListView.getRefreshableView().getFooterViewsCount()==1){
				mListView.getRefreshableView().addFooterView(mFootview);
			}
		}else{
			if(mListView.getRefreshableView().getFooterViewsCount() > 1){
				mListView.getRefreshableView().removeFooterView(mFootview);
			}
		}
	}

	private void init(LayoutInflater inflater) {
		mContext = getActivity().getApplicationContext();
		mListView = (PullToRefreshListView) mConvertView
				.findViewById(R.id.lv_shop_cart);
		mIvAllSelected = (ImageView) mConvertView
				.findViewById(R.id.iv_all_select);
		mIvAllSelected.setOnClickListener(this);
		mProductTotal = (TextView) mConvertView
				.findViewById(R.id.tv_goods_total);
		mProductPriceTotal = (TextView) mConvertView
				.findViewById(R.id.tv_price_total);
		mProductPriceTotalTitle1 = (TextView) mConvertView.findViewById(R.id.buttom_title_1);
		mProductPriceTotalTitle2 = (TextView) mConvertView.findViewById(R.id.buttom_titile_2);
		mTvAllSelected = (TextView) mConvertView.findViewById(R.id.tv_all_select);
		mBtnOrder = (RelativeLayout) mConvertView.findViewById(R.id.btn_order);
		mBtnOrder.setOnClickListener(this);
		mLoadingCover = (LoadingCover) mConvertView.findViewById(R.id.layout_loading_cover);
		mLoadingCover.setOnLoadingCoverRefreshListener(this);
		mLoadingData = new Dialog(getActivity(), R.style.DialogTheme);
		mLoadingData.setContentView(R.layout.loading_data_dialog);
		mLoadingData.setCanceledOnTouchOutside(false);
		mOfflineDialog = (OfflineDialog) inflater.inflate(R.layout.offline_dialog, null);
		initListener();
		
		mFootview = (RelativeLayout) inflater.inflate(R.layout.shoppingcart_no_data, null);
		TextView mNoData = (TextView) mFootview.findViewById(R.id.tv_nodata);
		RelativeLayout.LayoutParams noDataParams = (LayoutParams) mNoData.getLayoutParams();
		WindowManager wm = getActivity().getWindowManager();
		noDataParams.height = wm.getDefaultDisplay().getHeight() - Tools.dip2px(mContext, 160);
		
		mListView.setOnRefreshListener(this);
	}
	
	private void initListener() {
		mDeleteGoodsListener = new DeleteGoodsListener() {
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				mLoadingData.dismiss();
				ToastUtils.showToast(mContext, "删除商品失败, 请重试");
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineDialog.show();
				mLoadingData.dismiss();
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				if(mListView.isRefreshing()) {
					mListView.getLoadingLayoutProxy().refreshFailed();
				}
				mLoadingData.dismiss();
				mLoadingCover.onRefreshFailed(Define.MSG_NO_NETWORK);
			}
			
			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub
				mLoadingData.dismiss();
				checkNoData();
			}
			
			@Override
			public void onResponseSuccess(List<ShoppingCartInfo> shoppingCartInfos) {
				// TODO Auto-generated method stub
				List<ShoppingCartInfo> temp = new ArrayList<ShoppingCartInfo>();
				for(int i = 0;i < mDataList.size();i++){
					ShoppingCartInfo tempInfo = mDataList.get(i);
						if(!tempInfo.isSeleted()){
						temp.add(tempInfo);	
					}
				}
				
				mDataList.clear();
				mDataList.addAll(temp);
				mAdatper.notifyDataSetChanged();
//				if(temp2.size() == 0){
//					mOuter.rr_no_shopping.setVisibility(View.VISIBLE);
//				}
				countTotal();
				countIsAllSeleted();
				checkNoData();
				mLoadingData.dismiss();
				mLoadingCover.onRefreshSuccess();
				if(mListView.isRefreshing()) {
					mListView.getLoadingLayoutProxy().refreshSuccess();
				}
			}
		};
		
		mShoppingCartListener = new ShoppingCartListener() {
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed();
				if(mListView.isRefreshing()) {
					mListView.getLoadingLayoutProxy().refreshFailed();
				}
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineDialog.show();
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				if(mListView.isRefreshing()) {
					mListView.getLoadingLayoutProxy().refreshFailed();
				}
				mLoadingCover.onRefreshFailed(Define.MSG_NO_NETWORK);
			}
			
			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshSuccess();				
				if(mListView.isRefreshing()) {
					mListView.getLoadingLayoutProxy().refreshSuccess();
				}
				mDataList.clear();
				mAdatper.notifyDataSetChanged();
				countTotal();
				countIsAllSeleted();
				checkNoData();
			}
			
			@Override
			public void onResponseSuccess(List<ShoppingCartInfo> shoppingCartListeners) {
				//有数据可能就是下来操作了, 有时间也可以换成RequestCode.Pull判断
				if(mDataList.size() > 0) {
					for(int i = 0; i < shoppingCartListeners.size(); i++){
						ShoppingCartInfo info = shoppingCartListeners.get(i);
						for(int j = 0; j < mDataList.size(); j++){
							ShoppingCartInfo tempInfo = mDataList.get(j);
							if(tempInfo.getProductId() == info.getProductId()){
								if(tempInfo.isSeleted()){
									info.setSeleted(true);
								}
							}
								
						}
					}
				
				}
				if(immediate){
					for(int i = 0; i < shoppingCartListeners.size(); i++){
						ShoppingCartInfo info = shoppingCartListeners.get(i);
						if(info.getProductId() == immediateProductId&&info.getShopId() == immediateShopId){
							info.setSeleted(true);
							immediate = false;
							break;
						}
					}
				}
				
				mDataList.clear();
				mDataList.addAll(shoppingCartListeners);
				mAdatper.notifyDataSetChanged();
				mLoadingCover.onRefreshSuccess();
				checkNoData();
				countTotal();
				countIsAllSeleted();
				
				mLoadingCover.onRefreshSuccess();
				if(mListView.isRefreshing()) {
					mListView.getLoadingLayoutProxy().refreshSuccess();
				}
			}
		};
	}

	private void loadData() {
		IShoppingCart.getInstance().getShoppingCart(mShoppingCartListener);
	}

	private static class MyShoppingCartListener extends ShoppingCartListener {
		private FragmentShoppingCart mOuter;

		public MyShoppingCartListener(FragmentShoppingCart outer) {
			this.mOuter = outer;
		}

		public void release() {
			new WeakReference<FragmentShoppingCart>(mOuter);
		}

		@Override
		public void onResponseSuccess(
				List<ShoppingCartInfo> shoppingCartListeners) {
			if (mOuter == null || mOuter.isRemoving()) {
				return;
			}
			switch (requestCode) {
			case FIRST:
				mOuter.mDataList.clear();
				mOuter.mDataList.addAll(shoppingCartListeners);
				mOuter.mAdatper.notifyDataSetChanged();
				mOuter.mLoadingCover.onRefreshSuccess();
				mOuter.checkNoData();
				mOuter.countTotal();
				mOuter.countIsAllSeleted();
				break;
			case PULL:
				for(int i = 0;i< shoppingCartListeners.size();i++){
					ShoppingCartInfo info = shoppingCartListeners.get(i);
					for(int j = 0;j <mOuter.mDataList.size(); j++){
						ShoppingCartInfo tempInfo = mOuter.mDataList.get(j);
						if(tempInfo.getProductId() == info.getProductId()){
							if(tempInfo.isSeleted()){
								info.setSeleted(true);
							}
						}
							
					}
				}
				mOuter.mDataList.clear();
				mOuter.mDataList.addAll(shoppingCartListeners);
				mOuter.mAdatper.notifyDataSetChanged();
				mOuter.mLoadingCover.onRefreshSuccess();
				mOuter.checkNoData();
				mOuter.countTotal();
				mOuter.countIsAllSeleted();
				mOuter.mListView.getLoadingLayoutProxy().refreshSuccess();
				break;

			case UPDATA:
				List<ShoppingCartInfo> temp3 = new ArrayList<ShoppingCartInfo>();
				for(int i = 0;i<mOuter.mDataList.size();i++){
					ShoppingCartInfo tempInfo = mOuter.mDataList.get(i);
					for(int j = 0;j<shoppingCartListeners.size();j++){
						ShoppingCartInfo info = shoppingCartListeners.get(j);
						if(tempInfo.getShopId() == info.getShopId()&&tempInfo.getProductId() == info.getProductId()){
							tempInfo.setAddNum(0);
							tempInfo.setBuyNum(info.getBuyNum());
						}
					}
					temp3.add(tempInfo);
				}
				mOuter.mDataList.clear();
				mOuter.mDataList.addAll(temp3);
				mOuter.mAdatper.notifyDataSetChanged();
//				if(temp2.size() == 0){
//					mOuter.rr_no_shopping.setVisibility(View.VISIBLE);
//				}
				mOuter.countTotal();
				mOuter.countIsAllSeleted();
				
//				mOuter.mProgressDialog.dismiss();
				mOuter.tvEdit.setText("修改");
				mOuter.isEditable = false;
				mOuter.mAdatper.setEditable(mOuter.isEditable);
				mOuter.mProductPriceTotalTitle1.setVisibility(View.VISIBLE);
				mOuter.mProductPriceTotalTitle2.setVisibility(View.VISIBLE);
				mOuter.mProductPriceTotal.setVisibility(View.VISIBLE);
				mOuter.mIvAllSelected.setVisibility(View.VISIBLE);
				mOuter.mTvAllSelected.setVisibility(View.VISIBLE);
//				if(mOuter.isEditable){
//					mOuter.mBtnOrder.setText("删除");
//				}else{
//					mOuter.mBtnOrder.setText("结账");
//				}
				mOuter.mLoadingData.dismiss();
				mOuter.checkNoData();
				break;
			}
			
		}

		@Override
		public void onNoMoreData() {
			// TODO Auto-generated method stub
			if (mOuter == null || mOuter.isRemoving()) {
				return;
			}
			switch (requestCode) {
			case FIRST:
				mOuter.mLoadingCover.onRefreshSuccess();
				mOuter.checkNoData();
				break;
			case PULL:
				mOuter.mDataList.clear();
				mOuter.mAdatper.notifyDataSetChanged();
				mOuter.mListView.getLoadingLayoutProxy().refreshSuccess();
				mOuter.checkNoData();
				break;
			case UPDATA:
				mOuter.mLoadingData.dismiss();
				mOuter.checkNoData();
				break;

			default:
				break;
			}
		}

		@Override
		public void onNoNetWork() {
			// TODO Auto-generated method stub
			if (mOuter == null || mOuter.isRemoving()) {
				return;
			}
			Toast.makeText(mOuter.getActivity(), Define.MSG_NO_NETWORK, Toast.LENGTH_SHORT).show();
			switch (requestCode) {
			case FIRST:
				mOuter.mLoadingCover.onRefreshFailed();
				break;
			case PULL:
				mOuter.mListView.getLoadingLayoutProxy().refreshFailed();
				break;

			case UPDATA:
				mOuter.mLoadingData.dismiss();
				break;

			default:
				break;
			}
		}

		@Override
		public void onOffline() {
			// TODO Auto-generated method stub
			if (mOuter == null || mOuter.isRemoving()) {
				return;
			}
			mOuter.mOfflineDialog.show();
		}

		@Override
		public void onResponseFailed() {
			// TODO Auto-generated method stub
			if (mOuter == null || mOuter.isRemoving()) {
				return;
			}
			switch (requestCode) {
			case FIRST:
				mOuter.mLoadingCover.onRefreshFailed();
				break;
//			case DELETE:
//				mOuter.mLoadingData.dismiss();
//				break;
			case UPDATA:
				mOuter.mLoadingData.dismiss();
				break;

			default:
				break;
			}
			Toast.makeText(mOuter.getActivity(), "网络请求失败，请重试", Toast.LENGTH_SHORT).show();
		}

	}

	private static class MyUpdataUI implements UpdataUI {
		private FragmentShoppingCart mOuter;

		public MyUpdataUI(FragmentShoppingCart outer) {
			this.mOuter = outer;
		}

		public void release() {
			new WeakReference<FragmentShoppingCart>(mOuter);
		}

		@Override
		public void update() {
			// 计算是否全部选中，选中的商品书，总价
			if (mOuter == null || mOuter.isRemoving()) {
				return;
			}
			mOuter.countIsAllSeleted();
			mOuter.countTotal();
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_all_select:
			if (mIsAllseleted) {
				for (int i = 0; i < mDataList.size(); i++) {
					ShoppingCartInfo info = mDataList.get(i);
					info.setSeleted(false);
				}
				mIsAllseleted = false;
			} else {
				for (int i = 0; i < mDataList.size(); i++) {
					ShoppingCartInfo info = mDataList.get(i);
					info.setSeleted(true);
				}
				mIsAllseleted = true;
			}
			if (mIsAllseleted) {
				mIvAllSelected
						.setBackgroundResource(R.drawable.ic_shopping_selected);
			} else {
				mIvAllSelected
						.setBackgroundResource(R.drawable.ic_shopping_unselected);
			}
			countTotal();
			mAdatper.notifyDataSetChanged();
			break;
		case R.id.btn_order:
			if(isEditable){
				mDeleteStr = "";
					JSONArray orderArray = new JSONArray();
					for(int i = 0;i < mDataList.size();i++){
						ShoppingCartInfo info = mDataList.get(i);
						if(info.isSeleted()){
							JSONObject order = new JSONObject();
							try {
								order.put("act_id", info.getActId());
								order.put("shop_id", info.getShopId());
								order.put("product_id", info.getProductId());
								order.put("num", info.getBuyNum());
								//order.put("isHot", info.getIshot());
							} catch (JSONException e) {
								e.printStackTrace();
							}
							orderArray.put(order);
						}
					}
					if(orderArray.length()>0){
						mLoadingData.show();
						mDeleteStr = Tools.Base64Encode(orderArray.toString());//Base64.encodeToString(orderArray.toString().getBytes(), Base64.DEFAULT);
						IShoppingCart.getInstance().deleteGoods(mDeleteStr, mDeleteGoodsListener);
					}else{
						Toast.makeText(getActivity(), "请先选择要删除的商品", 0).show();
					}
			}else{
				JSONArray orderArray = new JSONArray();
				for(int i = 0;i < mDataList.size();i++){
					ShoppingCartInfo info = mDataList.get(i);
					if(info.isSeleted()){
						JSONObject order = new JSONObject();
						try {
							order.put("act_id", info.getActId());
							order.put("shop_id", info.getShopId());
							order.put("product_id", info.getProductId());
							order.put("num", info.getBuyNum());
							//order.put("isHot", info.getIshot());
						} catch (JSONException e) {
							e.printStackTrace();
						}
						orderArray.put(order);
					}
				}
				if(orderArray.length()>0){
					Intent intent = new Intent(getActivity(), OrderConfirmation.class);
					intent.putExtra("orderInfo", orderArray.toString());
					startActivityForResult(intent, 1);
				}else{
					Toast.makeText(getActivity(), "请先选择要购买的商品", 0).show();
				}
			}
			break;
		default:
			break;
		}
	}

	private void countIsAllSeleted() {
		mIsAllseleted = true;
		for (int i = 0; i < mDataList.size(); i++) {
			ShoppingCartInfo info = mDataList.get(i);
			if (!info.isSeleted()) {
				mIsAllseleted = false;
				break;
			}
		}
		if(mDataList.size() == 0){
			mIsAllseleted = false;
		}
		if (mIsAllseleted) {
			mIvAllSelected
					.setBackgroundResource(R.drawable.ic_shopping_selected);
		} else {
			mIvAllSelected
					.setBackgroundResource(R.drawable.ic_shopping_unselected);
		}

	}

	private void countTotal() {
		mProductTotalNum = 0;
		mProductPriceTotalNum = 0;

		for (int i = 0; i < mDataList.size(); i++) {
			ShoppingCartInfo info = mDataList.get(i);
			if (!info.isSeleted()) {
				continue;
			}
			mProductTotalNum += (info.getBuyNum() + info.getAddNum());
			mProductPriceTotalNum += (info.getBuyNum() + info.getAddNum())
					* info.getSalePrice();
		}
//		mProductTotal.setText(mProductTotalNum + "");
		mProductTotal.setText("去结算("+mProductTotalNum + ")");
		
		mProductPriceTotal.setText(getDoubleString(mProductPriceTotalNum));
	}

	private String getDoubleString(double mProductPrice) {
		DecimalFormat df = new DecimalFormat("0.00");
		return df.format(mProductPrice);
	}


	@Override
	public void onLoadingCoverRefresh() {
		IShoppingCart.getInstance().getShoppingCart(mShoppingCartListener);
	}


	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		IShoppingCart.getInstance().getShoppingCart(mShoppingCartListener);
	}
	
	private class RefreshReceiver extends BroadcastReceiver {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			immediateShopId = intent.getIntExtra("shopId", 0);
			immediateProductId = intent.getIntExtra("productId", 0);
			immediate = intent.getBooleanExtra("immediate", false);
			CrashHandler.d(TAG, "收到刷新购物车广播, immediateShopId = " + immediateShopId);
			loadData();
		}
	}
	public void autoRefresh(){
		mDataList.clear();
		countTotal();
		countIsAllSeleted();
		checkNoData();
		loadData();
	}
}
